<script setup>
import { ref, watch, computed, onMounted } from 'vue'
import { Delete, Plus } from '@element-plus/icons-vue'
import { templateAPI } from '@/services/api'
import { ElMessage } from 'element-plus'
import { chartColors } from '@/config/colors'
import AddTemplateDialog from './AddTemplateDialog.vue'
import { useTemplateStore } from '@/stores/template'


const props = defineProps({
  settings: {
    type: Object,
    required: true
  }
})

// 只保留一个 defineEmits
const emit = defineEmits(['update:settings', 'draw-curve'])

const showAddDialog = ref(false)
const experimentOptions = ref([])
const channelOptions = ref([])
const loading = ref(false)
const templateStore = useTemplateStore()

// 获取实验列表
const fetchExperiments = async () => {
  loading.value = true
  try {
    const response = await templateAPI.getExperiments()
    experimentOptions.value = response.data
  } catch (error) {
    console.error('获取实验列表失败:', error)
    ElMessage.error('获取实验列表失败')
  } finally {
    loading.value = false
  }
}

// 监听实验编号变化
const handleExperimentChange = async (experimentId) => {
  if (!experimentId) {
    const newSettings = { ...props.settings }
    newSettings.experimentName = ''
    newSettings.timeRange.start = ''
    newSettings.timeRange.end = ''
    emit('update:settings', newSettings)
    channelOptions.value = []
    return
  }

  const selectedExperiment = experimentOptions.value.find(
    exp => exp.experiment_id === experimentId
  )
  
  const newSettings = { ...props.settings }
  if (selectedExperiment) {
    newSettings.experimentName = selectedExperiment.experiment_name
  }

  try {
    const timeResponse = await templateAPI.getExperimentInfo(experimentId)
    newSettings.timeRange.start = timeResponse.data.start_time
    newSettings.timeRange.end = timeResponse.data.end_time

    const channelResponse = await templateAPI.getExperimentChannels(experimentId)
    channelOptions.value = channelResponse.data

    if (newSettings.channels.length === 1 && 
        (!newSettings.channels[0].experimentId || newSettings.channels[0].experimentId === '')) {
      newSettings.channels[0].experimentId = experimentId
    }
    emit('update:settings', newSettings)
  } catch (error) {
    console.error('获取实验信息失败:', error)
    ElMessage.error('获取实验信息失败')
  }
}

// 添加新通道
const addChannel = () => {
  const newSettings = { ...props.settings }
  newSettings.channels.push({
    id: Date.now(),
    experimentId: props.settings.experimentId,
    channel: '',
    transform: '',
    unit: '',
    position: '1',
    color: chartColors[newSettings.channels.length % chartColors.length],
    enabled: true
  })
  emit('update:settings', newSettings)
}

// 颜色选择器的选项
const colorOptions = computed(() => {
  return chartColors.map(color => ({
    value: color,
    style: { backgroundColor: color }
  }))
})

const removeChannel = (index) => {
  if (props.settings.channels.length > 1) {
    const newSettings = { ...props.settings }
    newSettings.channels.splice(index, 1)
    emit('update:settings', newSettings)
  }
}

const handleAddTemplate = async (templateData) => {
  try {
    await templateAPI.create(templateData)
    ElMessage({
      ...templateStore.messageConfig,
      type: 'success',
      message: '模板添加成功'
    })
    showAddDialog.value = false
  } catch (error) {
    // 处理错误信息
    let errorMessage = '添加模板失败'
    if (error.response?.data) {
      // 如果是字段验证错误
      if (typeof error.response.data === 'object') {
        const errors = []
        for (const [field, fieldErrors] of Object.entries(error.response.data)) {
          if (Array.isArray(fieldErrors)) {
            errors.push(fieldErrors[0])
          } else if (typeof fieldErrors === 'string') {
            errors.push(fieldErrors)
          }
        }
        if (errors.length > 0) {
          errorMessage = errors.join('; ')
        }
      } else if (error.response.data.message) {
        errorMessage = error.response.data.message
      } else if (error.response.data.error) {
        errorMessage = error.response.data.error
      }
    }
    
    ElMessage({
      ...templateStore.messageConfig,
      type: 'error',
      message: errorMessage
    })
  }
}

onMounted(() => {
  fetchExperiments()
})

// 当本地数据变化时，触发更新
const updateSettings = (newSettings) => {
  emit('update:settings', {...newSettings})
}
</script>

<template>
  <div class="curve-settings">
    <div class="settings-header">
      <div class="input-row">
        <el-select
          v-model="settings.experimentId"
          filterable
          clearable
          placeholder="请选择实验编号"
          style="width: 200px"
          @change="handleExperimentChange"
          :loading="loading"
        >
          <el-option
            v-for="item in experimentOptions"
            :key="item.experiment_id"
            :label="item.experiment_id"
            :value="item.experiment_id"
          />
        </el-select>
        <el-input
          v-model="settings.experimentName"
          placeholder="实验名称"
          style="width: 200px"
          disabled
        />
        <el-date-picker 
          v-model="settings.timeRange.start" 
          type="datetime" 
          placeholder="开始时间"
          :value-format="'X'"
          :format="'YYYY-MM-DD HH:mm:ss'"
          style="width: 200px"
        />
        <el-date-picker 
          v-model="settings.timeRange.end" 
          type="datetime" 
          placeholder="结束时间"
          :value-format="'X'"
          :format="'YYYY-MM-DD HH:mm:ss'"
          style="width: 200px"
        />
      </div>
    </div>

    <div class="channels-table">
      <el-table :data="settings.channels" border>
        <el-table-column label="序号" width="70">
          <template #default="{ $index }">
            {{ $index + 1 }}
          </template>
        </el-table-column>
        <el-table-column label="实验编号">
          <template #default="{ row }">
            <el-input v-model="row.experimentId" />
          </template>
        </el-table-column>
        <el-table-column label="通道" prop="channel">
            <template #default="{ row }">
                <el-select 
                v-model="row.channel"
                filterable
                clearable
                placeholder="请选择通道"
                >
                <el-option
                    v-for="channel in channelOptions"
                    :key="channel.channel_name"
                    :label="channel.channel_name"
                    :value="channel.channel_name"
                />
                </el-select>
            </template>
        </el-table-column>
        <el-table-column label="单位">
          <template #default="{ row }">
            <el-input v-model="row.unit" />
          </template>
        </el-table-column>
        <el-table-column label="位置" width="100">
          <template #default="{ row }">
            <el-input v-model="row.position" />
          </template>
        </el-table-column>
        <el-table-column label="颜色" width="100">
          <template #default="{ row }">
            <el-color-picker v-model="row.color" />
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120">
            <template #default="{ $index }">
                <div class="operation-buttons">
                <el-icon 
                    class="operation-icon delete-icon"
                    :class="{ 'disabled': settings.channels.length === 1 }"
                    @click="settings.channels.length > 1 && removeChannel($index)"
                >
                    <Delete />
                </el-icon>
                <el-icon 
                    v-if="$index === settings.channels.length - 1"
                    class="operation-icon add-icon"
                    @click="addChannel"
                >
                    <Plus />
                </el-icon>
                </div>
            </template>
            </el-table-column>
      </el-table>
    </div>

    <div class="button-group">
      <el-button 
        type="primary" 
        @click="$emit('draw-curve')"
        :disabled="!settings.experimentId || !settings.channels.length"
      >
        绘制曲线
      </el-button>
      <el-button 
        type="success" 
        @click="showAddDialog = true"
      >
        加入模板
      </el-button>
    </div>

    <!-- 添加模板对话框 -->
    <AddTemplateDialog
      v-model="showAddDialog"
      :settings="settings"
      @submit="handleAddTemplate"
    />
  </div>
</template>

<style scoped>
.curve-settings {
  height: 100%;
  display: flex;
  flex-direction: column;
  padding: 5px;
}

.settings-header {
  margin-bottom: 24px;
}

.input-row {
  display: flex;
  gap: 16px;
  align-items: center;
}

.channels-table {
  flex: 1;
  overflow: auto;
  margin-bottom: 24px;
}

.button-group {
  display: flex;
  gap: 12px;
  justify-content: center;
  padding-bottom: 8px;
}

/* 美化表格样式 */
:deep(.el-table) {
  --el-table-border-color: #dcdfe6;
  --el-table-header-bg-color: #f5f7fa;
}

:deep(.el-table th) {
  background-color: var(--el-table-header-bg-color);
  font-weight: 600;
}

:deep(.el-table td) {
  padding: 8px 0;
}

/* 输入框统一样式 */
:deep(.el-input__inner),
:deep(.el-select__input) {
  height: 32px;
  line-height: 32px;
}

/* 操作按钮样式保持不变 */
.operation-buttons {
  display: flex;
  gap: 12px;
  justify-content: center;
}

.operation-icon {
  font-size: 18px;
  cursor: pointer;
  transition: all 0.3s;
}

.delete-icon {
  color: #f56c6c;
}

.delete-icon:hover {
  color: #ff4d4f;
}

.delete-icon.disabled {
  color: #c0c4cc;
  cursor: not-allowed;
}

.add-icon {
  color: #409eff;
}

.add-icon:hover {
  color: #66b1ff;
}
</style>
